#include "tictactoe.h"
#include <QDebug>
#include <QTime>
#include <QRandomGenerator>
#include "widget.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include "http.h"
#include "image.h"
#include "mainwindow.h"

#define Photo "{#002P2150T1500!#001P2100T1500!#000P2165T1500!#003P1500T1500!}"

static const int get_x = 100;
static const int get_y = 0;
static const int get_z = 50;
static const int put_z = 50;
static const int move_time = 1500;
static const int base_x = 200;
static const int base_y = 100;
static const int spacing = 100;
static int a = 0,b = 0;

TicTacToe::TicTacToe(QWidget *parent) :
    QWidget(parent)
{
    setWindowTitle("Tic-Tac-Toe");
    QGridLayout* layout = new QGridLayout(this);
    QFont buttonFont("Arial", 24, QFont::Bold);
    ww.show();

    for (int i = 0; i < 9; ++i) {
        buttons[i] = new QPushButton("");
        buttons[i]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        buttons[i]->setFont(buttonFont);
        //connect(buttons[i], &QPushButton::clicked, this, &TicTacToe::buttonClicked);
        layout->addWidget(buttons[i], i / 3, i % 3);
        board[i] = 0;
    }
    currentPlayer = 1;

    ResetButton = new QPushButton(this);
    ResetButton->setText("复位!");

    connect(ResetButton, &QPushButton::clicked, this, [this](){
        w.sendCommand(Photo, "拍照");
        //w.sendCommand("#255P1500T2000!", "复位");
    });

    // 初始化定时器，定期检查识别结果
    recognitionCheckTimer = new QTimer(this);
    connect(recognitionCheckTimer, &QTimer::timeout, this, &TicTacToe::checkRecognitionChanges);
    recognitionCheckTimer->start(1000); // 每隔 1000 毫秒 (1秒) 检查一次

    previousRecognitionState = getRecognitionState(); // 初始化上一次的识别状态
    updateBoardUI(); // 初始化时根据识别结果更新棋盘
}

TicTacToe::~TicTacToe()
{
}

QString TicTacToe::getRecognitionState()
{
    QString state;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            state += ww.recognizedChars[i][j];
        }
    }
    return state;
}

void TicTacToe::updateBoardUI()
{ 
    a = 0; b = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            int index = i * 3 + j;
            if (ww.recognizedChars[i][j] == '1') {
                buttons[index]->setText("X");
                a++;
                board[index] = 1;
            } else if (ww.recognizedChars[i][j] == '2') {
                buttons[index]->setText("O");
                b++;
                board[index] = 2;
            } else {
                buttons[index]->setText("");
                board[index] = 0;
            }
        }
    }
    if(a > b)
    {
        currentPlayer = 2;
        if(a == 5 && b == 4)
        {
            qDebug() << "wwwwwwwwwwwwwwww";
            QMessageBox::information(this, "Game Over", "It's a draw!");
            resetGame();
            a = 0;
            b = 0;
            return;
        }
        makeAIMove();
    }
    else
    {
        ww.timerStart();
        makeAIMove();
    }
}

void TicTacToe::checkRecognitionChanges()
{
    QString currentRecognitionState = getRecognitionState();
    if (currentRecognitionState != previousRecognitionState) {
        qDebug() << "识别结果发生变化，正在更新棋盘 UI";
        updateBoardUI();
        previousRecognitionState = currentRecognitionState;
    }
}

void TicTacToe::buttonClicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    int index = -1;
    for (int i = 0; i < 9; ++i) {
        if (buttons[i] == button) {
            index = i;
            break;
        }
    }

    if (index != -1 && board[index] == 0 && currentPlayer == 1) {
        buttons[index]->setText("X");
        board[index] = 1;
        ww.recognizedChars[index / 3][index % 3] = '1'; // 更新识别结果

        if (checkWin(1)) {
            QMessageBox::information(this, "Game Over", "You win!");
            resetGame();
            return;
        }

        if (isBoardFull()) {
            QMessageBox::information(this, "Game Over", "It's a draw!");
            resetGame();
            return;
        }

        currentPlayer = 2;
        makeAIMove();
    }
}

void TicTacToe::makeAIMove()
{
    if (currentPlayer == 2) {
        qDebug() << "#####!!!!!";
        int bestMove = findBestMove();
        if (bestMove != -1) {
            w.actionGroupGet(0,135,20, move_time);
            QTimer::singleShot(3*move_time, this, [this, bestMove]() {
            w.actionGroupGet(get_x, get_y, get_z, move_time);

            int row = bestMove / 3;
            int col = bestMove % 3;

            w.BYxyPutPro(row,col,move_time);

            QTimer::singleShot(3*move_time, this, [this, bestMove]() {

                w.sendCommand(Photo, "拍照");

                });
            ww.timerStart();

            //ww.captureAndOpenImage();
            //ww.onImageCaptured();
            });
            buttons[bestMove]->setText("O");
            board[bestMove] = 2;
            ww.recognizedChars[bestMove / 3][bestMove % 3] = '2'; // 更新识别结果

            if (checkWin(2)) {
                QMessageBox::information(this, "Game Over", "我赢了!");
                resetGame();
                return;
            }

            if (isBoardFull()) {
                QMessageBox::information(this, "Game Over", "平局!");
                resetGame();
                return;
            }
/*
            for(int i = 0; i < 3; i++)
            {
                for(int j = 0; j < 3; j++)
                {
                    ww.recognizedChars[i][j] = buttons[i*3+j]->text()[0];
                }
            }*/
            currentPlayer = 1;
        }
    }
}

bool TicTacToe::checkWin(int player)
{
    for (int i = 0; i < 3; ++i) {
        if (board[i * 3] == player && board[i * 3] == board[i * 3 + 1] && board[i * 3] == board[i * 3 + 2]) {
            return true;
        }
    }

    for (int i = 0; i < 3; ++i) {
        if (board[i] == player && board[i] == board[i + 3] && board[i] == board[i + 6]) {
            return true;
        }
    }

    if (board[0] == player && board[0] == board[4] && board[0] == board[8]) {
        return true;
    }
    if (board[2] == player && board[2] == board[4] && board[2] == board[6]) {
        return true;
    }

    return false;
}

bool TicTacToe::isBoardFull()
{
    for (int i = 0; i < 9; ++i) {
        if (board[i] == 0) {
            return false;
        }
    }
    return true;
}

void TicTacToe::resetGame()
{
    for (int i = 0; i < 9; ++i) {
        buttons[i]->setText("");
        board[i] = 0;
        ww.recognizedChars[i / 3][i % 3] = '0'; // 同时重置识别结果
    }
    currentPlayer = 1;
}

int TicTacToe::findBestMove()
{
    for (int i = 0; i < 9; ++i) {
        if (board[i] == 0) {
            board[i] = 2;
            if (checkWin(2)) {
                board[i] = 0;
                return i;
            }
            board[i] = 0;
        }
    }

    for (int i = 0; i < 9; ++i) {
        if (board[i] == 0) {
            board[i] = 1;
            if (checkWin(1)) {
                board[i] = 0;
                return i;
            }
            board[i] = 0;
        }
    }

    if (board[4] == 0) {
        return 4;
    }

    QVector<int> corners = {0, 2, 6, 8};
    QRandomGenerator rng(QTime::currentTime().msec());
    std::random_shuffle(corners.begin(), corners.end(), [&rng](int n) {
        return rng.bounded(n);
    });
    for (int corner : corners) {
        if (board[corner] == 0) {
            return corner;
        }
    }

    QVector<int> availableMoves;
    for (int i = 0; i < 9; ++i) {
        if (board[i] == 0) {
            availableMoves.append(i);
        }
    }
    if (!availableMoves.isEmpty()) {
        return availableMoves[rng.bounded(availableMoves.size())];
    }

    return -1;
}

// 将棋盘行列转换为机械臂坐标 (需要根据实际情况调整)
void TicTacToe::mapToArmCoords(int row, int col, int &x, int &y, int &z)
{
    x = base_x + col * spacing;
    y = base_y + row * spacing;
    z = put_z;
}
